#
# Copyright 2010 Steve Leach
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
#

from google.appengine.ext import db
from google.appengine.ext import webapp

from handlers import EveOpsHandler
from evedata import EveData, get_eve_data

class Site(db.Model):
	name = db.StringProperty(required=True)
	wh_class = db.IntegerProperty(default=0)
	category = db.StringProperty()
	wave_triggers = db.StringListProperty(default=[])
	author = db.StringProperty()

def add_sites_mappings(mappings):
	mappings.append(('/sites', SitesListHandler))
	mappings.append(('/viewsite', ViewSiteHandler))
	mappings.append(('/editsite', EditSiteHandler))
	mappings.append(('/newsite', NewSiteHandler))
	mappings.append(('/submitsite', SubmitSiteHandler))

def get_site_names():
	site_names = []
	sites = Site.all()
	for site in sites:
		site_names.append(site.name)
	site_names.append('Other')
	site_names.append('Multiple')
	return site_names

class SitesListHandler(EveOpsHandler):
	def get(self):  
		eve_data = get_eve_data(self.request.headers)

		if not self.authorised(eve_data):
			return	

		sites = Site.all()

		values = {'sites': sites, 'eve_data': eve_data, 'headers': self.request.headers}

		self.display_page( 'listsites.html', values )

class ViewSiteHandler(EveOpsHandler):
	def get(self):  
		eve_data = get_eve_data(self.request.headers)

		if not self.authorised(eve_data):
			return	

		if self.request.get('key'):
			site = Site.get(self.request.get('key'))
		else:
			site = Site.gql('WHERE name = :1', self.request.get('name'))

			if site.count() == 0:
				self.redirect('/error?msg=1003')
				return

			site = site.get()

		values = {'site': site, 'eve_data': eve_data, 'headers': self.request.headers}
			
		self.display_page( 'viewsite.html', values )

class NewSiteHandler(EveOpsHandler):
	def get(self):  
		eve_data = get_eve_data(self.request.headers)

		if not self.authorised(eve_data):
			return	

		site = Site(name='New site')
		site.author = eve_data.char_name
		key = site.put()

		self.redirect('/editsite?key='+str(key))

class EditSiteHandler(EveOpsHandler):
	def get(self):  
		eve_data = get_eve_data(self.request.headers)

		if not self.authorised(eve_data):
			return	

		site = Site.get(self.request.get('key'))

		values = {'site': site, 'eve_data': eve_data, 'headers': self.request.headers}
			
		self.display_page( 'editsite.html', values )

class SubmitSiteHandler(EveOpsHandler):
	def post(self):
		key = self.request.get('key')

		site = Site.get(self.request.get('key'))
		site.name = self.request.get('name')
		site.category = self.request.get('category')
		site.wh_class = int(self.request.get('wh_class'))
		site.wave_triggers = self.request.get('triggers').split('\n')
		site.put()

		self.redirect('/viewsite?key='+key)



